package com.nuanshui.heatedloan.credit.pay;


import com.aipg.common.AipgReq;
import com.aipg.common.AipgRsp;
import com.aipg.qvd.QVDReq;
import com.aipg.qvd.QVDRsp;
import com.aipg.rnp.*;
import com.aipg.singleacctvalid.ValidR;
import com.alibaba.fastjson.JSON;
import com.nuanshui.framework.lang.SysStringUtils;
import com.nuanshui.framework.security.DESC;
import com.nuanshui.framework.utils.LogUtil;
import com.nuanshui.heatedloan.constant.DubboCacheRegion;
import com.nuanshui.heatedloan.constant.ServiceConstant;
import com.nuanshui.heatedloan.credit.constant.TonlyConstant;
import com.nuanshui.heatedloan.credit.facade.AllinPayAuthService;
import com.nuanshui.heatedloan.credit.pay.behavior.PayBehavior;
import com.nuanshui.heatedloan.dal.IdTypeHandler;
import com.nuanshui.heatedloan.dubbo.extension.cache.manager.DubboCacheManager;
import com.nuanshui.heatedloan.middleware.async.util.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.Callable;

@Service(ServiceConstant.ALLINPAYAUTHSERVICE)
public class AllinPayAuthServiceImpl implements AllinPayAuthService,SmartInitializingSingleton {


    protected Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private AllinPayTool allinPayTool;

    @Autowired
    private DubboCacheManager cacheManager;

    public void queryUserAccount(final String id) {
        QVDReq req = new QVDReq();

        req.setMERCHANT_ID(PayContext.getContext().getAipgReq().getINFO().getMERCHANT_ID());
        req.setQUERY_SN(id);

        QVDRsp rep=null;
        PayContext context = allinPayTool.execute(TransRequestCode.TRX_CODE_UESRACCOUNT_QUERY, new Callable<QVDReq>() {

            public QVDReq call() {
                QVDReq req = new QVDReq();

                req.setMERCHANT_ID(PayContext.getContext().getAipgReq().getINFO().getMERCHANT_ID());
                req.setQUERY_SN(id);
                return req;
            }
        });

        if(context!=null)
        {
            rep=context.getData();
        }
    }

    /**
     * 账户实名验证(二/三/四要素)
     * @param request
     * @return
     */
    public void authUserAccount(PayRequest request) {

        request.setTransRequestCode(TransRequestCode.TRX_CODE_USERACCOUNT_AUTH);

//        allinPayTool.execute(request, new PayBehavior() {
//            @Override
//            public void internalInvoke(PayRequest request) {
//                ValidR trans = new ValidR();
//
//                AipgReq aipgReq=PayContext.getContext().getAipgReq();
//                trans.setMERCHANT_ID(aipgReq.getINFO().getMERCHANT_ID());
//
//
//                //账号类型  不填默认为银行卡00 [可空]
//                trans.setACCOUNT_TYPE(TonlyConstant.BANK_CARD);
//                //账号属性   0私人，1公司。不填时，默认为私人0
//                trans.setACCOUNT_PROP(TonlyConstant.PERSONAL_ACCOUNT);
//                //人民币：CNY, 港元：HKD，美元：USD。不填时，默认为人民币
//                //提交时间
//                trans.setSUBMIT_TIME(DateUtils.getDate("yyyyMMddHHmmss"));
//
//                //银行代码  存折必须填写
//                trans.setBANK_CODE(request.getBankCard().getCardBankCode());
//                //账号
//                trans.setACCOUNT_NO(DESC.decrypt3DES(request.getOrder().getMixCardNo()));
//                //账号名称
//                trans.setACCOUNT_NAME(request.getBankCard().getCardBankName());
//                //证件id   [可空]
//                trans.setID(DESC.decrypt3DES(request.getIdCard().getIdCard()));
//                //联系方式   [可空]
//                trans.setTEL(request.getBankCard().getMobileNo());
//
//                request.setTrxData(trans);
//
//            }
//        });

    }

    /**
     * 实名付申请
     * @param
     * @return
     */
    public RNPARET authTestRepayUserAccount() {

        RNPARET item=null;
        PayContext context=allinPayTool.execute(TransRequestCode.TRX_CODE_USERACCOUNT_AUTH_APPLY,
                new Callable<RNPA>() {

                    @Override
                    public RNPA call() throws Exception {


                        RNPA trans = new RNPA();

                        AipgReq aipgReq = PayContext.getContext().getAipgReq();
                        trans.setMERCHANT_ID(aipgReq.getINFO().getMERCHANT_ID());

                        //账号类型  不填默认为银行卡00 [可空]
                        trans.setACCOUNT_TYPE(TonlyConstant.BANK_CARD);
                        //账号属性   0私人，1公司。不填时，默认为私人0
                        trans.setACCOUNT_PROP(TonlyConstant.PERSONAL_ACCOUNT);
                        //人民币：CNY, 港元：HKD，美元：USD。不填时，默认为人民币
                        //提交时间
                        trans.setSUBMIT_TIME(DateUtils.getDate("yyyyMMddHHmmss"));

                        trans.setBANK_CODE("0104");
                        //账号
                        trans.setACCOUNT_NO("6013820800068188554");
                        //账号名称
                        trans.setACCOUNT_NAME("叶永青");
                        //证件id   [可空]
                        trans.setID("320683198011100010");
                        //联系方式   [可空]
                        trans.setTEL("13564600959");
                        trans.setID_TYPE("0");
                        //联系方式   [可空]


                        return trans;
                    }
                });

        if(context!=null)
        {
            item=context.getData();

            AipgRsp rsp=context.getAipgRsp();

            cacheManager.put(DubboCacheRegion.CACHE_CONSTANT_ALLINPAY_REPAY_VERIFY,
                    IdTypeHandler.encode(1),rsp.getINFO().getREQ_SN());

            LogUtil.info(log,"支付还款短信流程","流水号:"+rsp.getINFO().getREQ_SN());
            LogUtil.info(log,"支付还款短信流程","短信发送结果"+JSON.toJSONString(item));
        }

        if(item==null)
        {
            item=new RNPARET();
            item.setRET_CODE("-1");
            item.setERR_MSG("处理失败");
        }

        return item;
    }

    /**
     * 实名付申请
     * @param request
     * @return
     */
    public RNPARET authRepayUserAccount(PayRequest request) {
        request.setTransRequestCode(TransRequestCode.TRX_CODE_USERACCOUNT_AUTH_APPLY);

        RNPARET item=null;
        PayContext context=allinPayTool.execute(request,
                new Callable<RNPA>() {

                    @Override
                    public RNPA call() throws Exception {

                        PayRequest request = PayContext.getContext().getPayRequest();
                        RNPA trans = new RNPA();

                        AipgReq aipgReq = PayContext.getContext().getAipgReq();
                        trans.setMERCHANT_ID(aipgReq.getINFO().getMERCHANT_ID());


                        //账号类型  不填默认为银行卡00 [可空]
                        trans.setACCOUNT_TYPE(TonlyConstant.BANK_CARD);
                        //账号属性   0私人，1公司。不填时，默认为私人0
                        trans.setACCOUNT_PROP(TonlyConstant.PERSONAL_ACCOUNT);
                        //人民币：CNY, 港元：HKD，美元：USD。不填时，默认为人民币
                        //提交时间
                        trans.setSUBMIT_TIME(DateUtils.getDate("yyyyMMddHHmmss"));

                        //银行代码  存折必须填写
                        trans.setBANK_CODE(request.getBankCard().getCardBankCode());
                        //账号
                        trans.setACCOUNT_NO(DESC.decrypt3DES(request.getBankCard().getMixCardNo()));
                        //账号名称
                        trans.setACCOUNT_NAME(request.getIdCard().getCustomerName());
                        //证件id   [可空]
                        trans.setID(DESC.decrypt3DES(request.getIdCard().getIdCard()));
                        trans.setID_TYPE("0");
                        //联系方式   [可空]
                        trans.setTEL(request.getBankCard().getMobileNo());

                        return trans;
                    }
                });

        if(context!=null)
        {
            item=context.getData();

            AipgRsp rsp=context.getAipgRsp();

            cacheManager.putExpire(DubboCacheRegion.CACHE_CONSTANT_ALLINPAY_REPAY_VERIFY,
                    request.getOrder().getUserId(),300L,rsp.getINFO().getREQ_SN());

            LogUtil.info(log,"支付还款短信流程","流水号:"+rsp.getINFO().getREQ_SN());
            LogUtil.info(log,"支付还款短信流程","短信发送结果"+JSON.toJSONString(item));
        }

        if(item==null)
        {
            item=new RNPARET();
            item.setRET_CODE("-1");
            item.setERR_MSG("处理失败");
        }

        return item;
    }

    public RNPRRET authRepayUserAccountReSend(final String userId) {

        final String reqSn=(String)cacheManager.get(DubboCacheRegion.CACHE_CONSTANT_ALLINPAY_REPAY_VERIFY,userId);

        RNPRRET result=null;
        if(SysStringUtils.isNotEmpty(reqSn))
        {
            PayContext context=allinPayTool.execute(TransRequestCode.TRX_CODE_USERACCOUNT_AUTH_RESEND, new Callable<RNPR>() {

                @Override
                public RNPR call() throws Exception {

                    RNPR item=new RNPR();
                    AipgReq aipgReq=PayContext.getContext().getAipgReq();
                    item.setMERCHANT_ID(aipgReq.getINFO().getMERCHANT_ID());
                    item.setSRCREQSN(reqSn);
                    return item;
                }
            });
            if(context!=null)
            {
                result=context.getData();
            }

        }
        return result;
    }

    public RNPCRET authRepayUserAccountVerify(final String userId,final String verCode) {

        RNPCRET result = null;

        final String reqSn = (String) cacheManager.get(DubboCacheRegion.CACHE_CONSTANT_ALLINPAY_REPAY_VERIFY, userId);

        if (SysStringUtils.isEmpty(reqSn))
            return result;

        LogUtil.info(log, "支付还款短信流程", "短信验证开始 流水号:" + reqSn);
        LogUtil.info(log, "authRepayUserAccountVerify Sn:" + reqSn);


        PayContext context = allinPayTool.execute(TransRequestCode.TRX_CODE_USERACCOUNT_AUTH_VERIFY, new Callable<RNPR>() {

            @Override
            public RNPR call() throws Exception {

                RNPC item = new RNPC();
                AipgReq aipgReq = PayContext.getContext().getAipgReq();
                item.setMERCHANT_ID(aipgReq.getINFO().getMERCHANT_ID());
                item.setSRCREQSN(reqSn);
                item.setVERCODE(verCode);
                return item;
            }
        });

        if (context != null) {
            result = context.getData();

            LogUtil.info(log, "支付还款短信流程", "短信验证结束:" + JSON.toJSONString(result));
        }


        return result;
    }


    public void afterSingletonsInstantiated() {

       //authTestRepayUserAccount();
        //PayRequest request = new PayRequest();

        //request.setOrderNo("201707311159052401792");

        //authRepayUserAccount(request);

        //authRepayUserAccountVerify("1vfhi","3962");
    }

    //@Override
    public void afterPropertiesSet() throws Exception {
       // authRepayUserAccountVerify("1vfhi","1233");
    }
}
